package com.lzq.thread;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.UUID;
import org.junit.Test;

/**
 * @author 2019/7/2 16:50 by 刘赵强
 * Exception in thread "Thread-2" java.lang.ArrayIndexOutOfBoundsException: 15
 * at java.util.ArrayList.add(ArrayList.java:459)
 * at com.lzq.thread.ArrayListThreadTest$3.run(ArrayListThreadTest.java:44)
 * at java.lang.Thread.run(Thread.java:745)
 * 第1个元素为：0
 * 第2个元素为：1000
 * 第3个元素为：3000
 * 第4个元素为：1
 * <p>
 * https://blog.csdn.net/u012859681/article/details/78206494
 **/
public class ArrayListThreadTest {

    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        for (int i = 1; i <= 30; i++) {
            new Thread(()->{
                list.add(UUID.randomUUID().toString().substring(0,8));
                System.out.println(list);
            },String.valueOf(i)).start();
        }
    }

    public static void main2(String[] args) throws InterruptedException {
        final List<Integer> list = new ArrayList<>(); // 线程A将0-1000添加到list
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 1000; i++) {
                    list.add(i);
                    try {
                        Thread.sleep(1);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start(); // 线程B将1000-2000添加到列表
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 1000; i < 2000; i++) {
                    list.add(i);
                    try {
                        Thread.sleep(1);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 3000; i < 4000; i++) {
                    list.add(i);
                    try {
                        Thread.sleep(1);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
        Thread.sleep(1000);
        // 打印所有结果
        for (int i = 0; i < list.size(); i++) {
            System.out.println("第" + (i + 1) + "个元素为：" + list.get(i));
        }
    }
}
